package org.kotboot.typeHandler;

import org.kotboot.enums.*;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * code enum 枚举到数据库的映射，及反映射
 * jisong.sun 2017/8/23 18:19
 */
@MappedTypes({
        BoolState.class,
        PostageModel.class,
        ECommodityState.class,
        ESkuState.class,
        DictState.class})
@MappedJdbcTypes(JdbcType.TINYINT)
public class CodeEnumTypeHandler<E extends Enum<E> & CodeEnum<E>> extends BaseTypeHandler<CodeEnum> {

    private Class<CodeEnum> type;

    public CodeEnumTypeHandler(){}

    public CodeEnumTypeHandler(Class<CodeEnum> type){
        init(type);
    }

    public void init(Class<CodeEnum> type){
        if(type == null){
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    private CodeEnum convert(int code){
        CodeEnum[] enumConstants = type.getEnumConstants();
        for (CodeEnum codeEnum: enumConstants){
            if(codeEnum.code() == code){
                return codeEnum;
            }
        }
        return null;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, CodeEnum codeEnum, JdbcType jdbcType) throws SQLException {
        // baseTypeHandler已经帮我们做了parameter的null判断
        ps.setInt(i, codeEnum.code());
    }

    @Override
    public CodeEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return convert(rs.getInt(columnName));
    }

    @Override
    public CodeEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return convert(rs.getInt(columnIndex));
    }

    @Override
    public CodeEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return convert(cs.getInt(columnIndex));
    }
}
